<template>
  <div>
    <div class="image-to-video">
      <div class="content-wrapper">
        <!-- 左侧图片区域 -->
        <div class="left-panel">
          <div class="image-container">
            <img v-if="sourceImage" :src="sourceImage" alt="源图片" class="source-image" />
            <div v-else class="image-placeholder">
              <div class="placeholder-text">请选择图片</div>
            </div>
          </div>
        </div>

        <!-- 右侧控制面板 -->
        <div class="right-panel">
          <!-- 时间显示 -->
          <div class="time-display">
            {{ currentTime }}
          </div>

          <!-- 提示词输入 -->
          <div class="control-section">
            <label class="section-label">提示词（选填）</label>
            <el-input
              v-model="prompt"
              type="textarea"
              :rows="6"
              placeholder="详细描述您想要生成的视频内容（可选）"
              class="prompt-input"
              maxlength="1500"
              show-word-limit
            />
          </div>

          <!-- 质量选择 -->
          <div class="control-section">
            <label class="section-label">质量</label>
            <div class="quality-options">
              <el-radio-group v-model="quality">
                <el-radio label="Lite">Lite</el-radio>
                <el-radio label="Pro">Pro</el-radio>
                <el-radio label="Plus">Plus</el-radio>
                <el-radio label="Best">Best</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 时长选择 -->
          <div class="control-section">
            <label class="section-label">时长</label>
            <div class="duration-options">
              <el-radio-group v-model="duration">
                <el-radio label="5s">5s</el-radio>
                <el-radio label="10s">10s</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 生成数量 -->
          <div class="control-section">
            <label class="section-label">生成数量：{{ generateCount }}</label>
            <el-slider
              v-model="generateCount"
              :min="1"
              :max="4"
              :marks="{ 1: '1', 2: '2', 3: '3', 4: '4' }"
              class="count-slider"
            />
          </div>

          <!-- 负面提示词 -->
          <div class="control-section">
            <label class="section-label">负面提示词（选填）</label>
            <el-input
              v-model="negativePrompt"
              type="textarea"
              :rows="4"
              placeholder="列出您不想在视频中看到的内容类型，示例：动画、模糊、扭曲、低质量、拼贴、颗粒、计算机生成、扭曲......"
              class="negative-prompt-input"
            />
          </div>

          <!-- 预计消耗积分 -->
          <div class="control-section">
            <label class="section-label">预计消耗积分：{{ computedPoints }} 积分</label>
          </div>

          <!-- 生成按钮 -->
          <div class="generate-section">
            <el-button 
              type="primary" 
              size="large" 
              class="generate-btn"
              :loading="generating"
              @click="handleGenerate"
            >
              <el-icon><VideoCamera /></el-icon>
              生成
              <span class="points-text">{{ computedPoints }}积分</span>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 生成结果预览区域 -->
      <div v-if="generatedVideos.length > 0" class="result-section">
        <h3>生成结果</h3>
        <div class="video-grid">
          <div v-for="(video, index) in generatedVideos" :key="index" class="video-item">
            <video :src="video.url" controls class="result-video"></video>
            <div class="video-actions">
              <el-button size="small" @click="downloadVideo(video)">下载</el-button>
              <el-button size="small" @click="shareVideo(video)">分享</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoCamera } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 响应式数据
const sourceImage = ref('')
const currentTime = ref('')
const prompt = ref('')
const quality = ref('Pro')
const duration = ref('10s')
const generateCount = ref(1)
const negativePrompt = ref('')
const generating = ref(false)
const generatedVideos = ref([])

// 计算积分
const pointMap = {
  lite: { '5s': 8, '10s': 10 },
  pro: { '5s': 10.5, '10s': 13.5 },
  plus: { '5s': 13.5, '10s': 25 },
  best: { '5s': 25, '10s': 47 }
}

const computedPoints = computed(() => {
  const mode = quality.value.toLowerCase()
  const dur = duration.value
  const unit = pointMap[mode]?.[dur] || 0
  return unit * generateCount.value
})

// 更新时间显示
function updateTime() {
  const now = new Date()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  currentTime.value = `${month}-${day} ${hours}:${minutes}`
}

// 定时器
let timeInterval = null

// 生成视频
async function handleGenerate() {
  if (!sourceImage.value) {
    ElMessage.warning('请先选择源图片')
    return
  }

  generating.value = true

  try {
    // 获取token（如有全局token管理可替换）
    const token = localStorage.getItem('token') || ''

    // 请求接口
    const res = await fetch('https://ai.tianjing.site/server/productAnyShoot/task/startImage2Video', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      body: JSON.stringify({
        taskId: route.query.taskId,
        selectedImageKey: route.query.key,
        duration: parseInt(duration.value),
        mode: quality.value.toLowerCase(),
        generatingCount: generateCount.value,
        prompt: prompt.value,
        negativePrompt: negativePrompt.value,
        noticeUrl: ''
      })
    })
    const data = await res.json()
    if (data.code === 200) {
      ElMessage.success('视频生成任务已提交，请稍候...')
      // 跳转到万物生成列表
      router.push('/mask-editor/task-list')
    } else {
      throw new Error(data.msg || '生成失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '生成失败，请重试')
  } finally {
    generating.value = false
  }
}

// 下载视频
function downloadVideo(video) {
  const link = document.createElement('a')
  link.href = video.url
  link.download = `generated_video_${video.id}.mp4`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 分享视频
function shareVideo(video) {
  if (navigator.share) {
    navigator.share({
      title: '生成的视频',
      url: video.url
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(video.url)
    ElMessage.success('视频链接已复制到剪贴板')
  }
}

onMounted(() => {
  console.log('route.query:', route.query)
  if (route.query.image) {
    sourceImage.value = decodeURIComponent(route.query.image)
    console.log('decodeURIComponent(route.query.image):', sourceImage.value)
  }
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.image-to-video {
  min-height: 100vh;
  background: #18181c;
  color: #fff;
}

.content-wrapper {
  display: flex;
  min-height: calc(100vh - 60px);
}

.left-panel {
  width: 400px;
  padding: 20px;
  background: #23232a;
  border-right: 1px solid #333;
}

.image-container {
  width: 100%;
  height: 320px;
  border-radius: 12px;
  overflow: hidden;
  background: #18181c;
  display: flex;
  align-items: center;
  justify-content: center;
}

.source-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #23232a;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.3);
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
}

.right-panel {
  flex: 1;
  padding: 20px;
  background: #18181c;
}

.control-section {
  margin-bottom: 24px;
}

.section-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #fff;
}

.time-display {
  color: #888;
  font-size: 14px;
  margin-bottom: 16px;
}

.prompt-input {
  margin-bottom: 12px;
}

.quality-options,
.duration-options {
  display: flex;
  gap: 16px;
}

.count-slider {
  margin-top: 12px;
}

.negative-prompt-input {
  margin-top: 8px;
}

.generate-section {
  margin-top: 32px;
}

.generate-btn {
  width: 200px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  background: #409eff !important;
  border: none !important;
  border-radius: 12px !important;
  position: relative;
  padding-right: 80px !important;
}

.generate-btn:hover {
  background: #66b1ff !important;
}

.points-text {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  opacity: 1;
  padding-left: 12px;
  border-left: 1px solid rgba(255, 255, 255, 0.5);
}

.result-section {
  padding: 20px;
  background: #2a2a2a;
  margin-top: 20px;
}

.result-section h3 {
  margin-bottom: 16px;
  color: #fff;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.video-item {
  background: #1a1a1a;
  border-radius: 12px;
  overflow: hidden;
  padding: 12px;
}

.result-video {
  width: 100%;
  height: 200px;
  border-radius: 8px;
}

.video-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
  justify-content: center;
}

/* Element Plus 样式覆盖 */
:deep(.el-select .el-input__wrapper) {
  background: #333 !important;
  border-color: #555 !important;
}

:deep(.el-input__wrapper) {
  background: #333 !important;
  border-color: #555 !important;
}

:deep(.el-input__inner) {
  color: #fff !important;
}

:deep(.el-textarea__inner) {
  background: #333 !important;
  border-color: #555 !important;
  color: #fff !important;
}

:deep(.el-radio__label) {
  color: #fff !important;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background: #6c5ce7 !important;
  border-color: #6c5ce7 !important;
}

:deep(.el-slider__runway) {
  background: #333 !important;
}

:deep(.el-slider__button) {
  background: #6c5ce7 !important;
  border-color: #6c5ce7 !important;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background: #6c5ce7 !important;
}

:deep(.el-input__count) {
  background: transparent !important;
  color: #aaa !important;
  box-shadow: none !important;
}
</style> 